package com.atguigu.utils;

import com.google.common.base.CaseFormat;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtil2 {
    public static <T> List<T> getSelectResult(Connection connection, String sql, Class<T> clz, boolean lowerUnderscoreToLowerCamel) throws Exception{
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.execute();
        //获得元数据（列名，列数量），查询的结果
        ResultSetMetaData metaData = preparedStatement.getMetaData();
        int columnCount = metaData.getColumnCount();
        ArrayList<T> queryList = new ArrayList<>();
        ResultSet resultSet = preparedStatement.getResultSet();

        while (resultSet.next()) {
            T t = clz.newInstance();
            Field[] fields = clz.getDeclaredFields();
            for (int i = 0; i < columnCount; i++) {
                //获取列名，与反射获得的属性，映射赋值
                String columnName = metaData.getColumnName(i+1);
                if (lowerUnderscoreToLowerCamel){//是否要转换命名格式
                    columnName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL,metaData.getColumnName(i+1));
                }
                for (int i1 = 0; i1 < fields.length; i1++) {
                    Field field = fields[i1];
                    field.setAccessible(true);
                    if (columnName.equals(field.getName())){
                        field.set(t,resultSet.getString(i+1));
                    }
                }
            }
            queryList.add(t);//把一行数据以bean对象的结构存在数组中
        }
        preparedStatement.close();
        return queryList;
    }
}
